{% extends "base.html" %}

{% block title %}{{ post.title }} - 墨韵图书共享平台{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row">
        <!-- 主要内容区 -->
        <div class="col-md-8">
            <div class="card ink-card mb-4">
                <div class="card-body">
                    <!-- 帖子头部 -->
                    <div class="d-flex align-items-start mb-4">
                        <div class="me-3">
                            {% if post.author.avatar and post.author.avatar != 'default.png' %}
                            <img src="{{ url_for('static', filename='avatars/' + post.author.avatar) }}" 
                                 class="user-avatar-lg" alt="{{ post.author.username }}"
                                 onerror="this.onerror=null; this.parentElement.innerHTML='<div class=\'default-avatar-lg\'>{{ post.author.username[0]|upper }}</div>'">
                            {% else %}
                            <div class="default-avatar-lg">{{ post.author.username[0]|upper }}</div>
                            {% endif %}
                        </div>
                        <div class="flex-grow-1">
                            <h2 class="mb-2">{{ post.title }}</h2>
                            <div class="post-meta text-muted">
                                <span class="me-3">
                                    <i class="fas fa-user me-1"></i>{{ post.author.username }}
                                </span>
                                <span class="me-3">
                                    <i class="fas fa-clock me-1"></i>{{ post.created_at.strftime('%Y-%m-%d %H:%M') }}
                                </span>
                                {% if post.circle %}
                                <a href="{{ url_for('circle_detail', circle_id=post.circle.id) }}" 
                                   class="badge bg-primary text-decoration-none">
                                    <i class="fas fa-users me-1"></i>{{ post.circle.name }}
                                </a>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    
                    <!-- 帖子内容 -->
                    <div class="post-content mb-4">
                        {{ post.content|safe }}
                    </div>
                    
                    <!-- 帖子操作 -->
                    <div class="post-actions border-top pt-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <button class="btn btn-sm {% if is_liked %}btn-primary{% else %}btn-outline-primary{% endif %} me-2" 
                                        onclick="toggleLike()" id="likeBtn">
                                    <i class="fas fa-thumbs-up me-1"></i>
                                    <span id="likeText">{% if is_liked %}已点赞{% else %}点赞{% endif %}</span>
                                    <span class="ms-1" id="likeCount">({{ post.likes }})</span>
                                </button>
                                <button class="btn btn-sm {% if is_favorited %}btn-primary{% else %}btn-outline-primary{% endif %} me-2" 
                                        onclick="toggleFavorite()" id="favoriteBtn">
                                    <i class="fas fa-bookmark me-1"></i>
                                    <span id="favoriteText">{% if is_favorited %}已收藏{% else %}收藏{% endif %}</span>
                                    <span class="ms-1" id="favoriteCount">({{ post.favorites }})</span>
                                </button>
                                <button class="btn btn-sm btn-outline-primary me-2" onclick="focusComment()">
                                    <i class="fas fa-comment me-1"></i>评论
                                </button>
                            </div>
                            {% if current_user == post.author %}
                            <div>
                                <a href="{{ url_for('edit_post', post_id=post.id) }}" class="btn btn-sm btn-outline-secondary me-2">
                                    <i class="fas fa-edit me-1"></i>编辑
                                </a>
                                <button class="btn btn-sm btn-outline-danger" onclick="deletePost()">
                                    <i class="fas fa-trash me-1"></i>删除
                                </button>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="card ink-card">
                <div class="card-header ink-header">
                    <h5 class="mb-0">
                        <i class="fas fa-comments me-2"></i>评论 ({{ post.comments.count() }})
                    </h5>
                </div>
                <div class="card-body">
                    <!-- 评论表单 -->
                    <div class="comment-form mb-4">
                        <form action="{{ url_for('add_comment', post_id=post.id) }}" method="POST">
                            <div class="mb-3">
                                <textarea class="form-control ink-input" id="comment-input" 
                                          name="content" rows="3" placeholder="写下你的评论..." required></textarea>
                            </div>
                            <div class="text-end">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-2"></i>发表评论
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 评论列表 -->
                    <div class="comments-list">
                        {% for comment in post.comments %}
                        <div class="comment mb-3">
                            <div class="d-flex">
                                <div class="me-3">
                                    {% if comment.author.avatar and comment.author.avatar != 'default.png' %}
                                    <img src="{{ url_for('static', filename='avatars/' + comment.author.avatar) }}" 
                                         class="user-avatar" alt="{{ comment.author.username }}"
                                         onerror="this.onerror=null; this.parentElement.innerHTML='<div class=\'default-avatar\'>{{ comment.author.username[0]|upper }}</div>'">
                                    {% else %}
                                    <div class="default-avatar">{{ comment.author.username[0]|upper }}</div>
                                    {% endif %}
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <div class="comment-author">
                                            <strong>{{ comment.author.username }}</strong>
                                            <small class="text-muted ms-2">
                                                <i class="fas fa-clock"></i> {{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}
                                            </small>
                                        </div>
                                        {% if current_user == comment.author %}
                                        <div class="comment-actions">
                                            <button class="btn btn-sm btn-link text-danger" 
                                                    onclick="deleteComment({{ comment.id }})">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                        {% endif %}
                                    </div>
                                    <div class="comment-content">
                                        {{ comment.content }}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 侧边栏 -->
        <div class="col-md-4">
            <!-- 作者信息 -->
            <div class="card ink-card mb-4">
                <div class="card-header ink-header">
                    <h5 class="mb-0">作者信息</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        {% if post.author.avatar and post.author.avatar != 'default.png' %}
                        <img src="{{ url_for('static', filename='avatars/' + post.author.avatar) }}" 
                             class="user-avatar-lg me-3" alt="{{ post.author.username }}"
                             onerror="this.onerror=null; this.parentElement.innerHTML='<div class=\'default-avatar-lg me-3\'>{{ post.author.username[0]|upper }}</div>'">
                        {% else %}
                        <div class="default-avatar-lg me-3">{{ post.author.username[0]|upper }}</div>
                        {% endif %}
                        <div>
                            <h5 class="mb-1">{{ post.author.username }}</h5>
                            <small class="text-muted">
                                {% if post.author.is_teacher %}
                                <i class="fas fa-chalkboard-teacher"></i> 教师
                                {% else %}
                                <i class="fas fa-user-graduate"></i> 学生
                                {% endif %}
                            </small>
                        </div>
                    </div>
                    {% if post.author.bio %}
                    <p class="card-text">{{ post.author.bio }}</p>
                    {% endif %}
                </div>
            </div>

            <!-- 相关帖子 -->
            {% if post.circle %}
            <div class="card ink-card">
                <div class="card-header ink-header">
                    <h5 class="mb-0">相关帖子</h5>
                </div>
                <div class="list-group list-group-flush">
                    {% for related_post in post.circle.posts %}
                        {% if related_post != post %}
                        <a href="{{ url_for('view_post', post_id=related_post.id) }}" 
                           class="list-group-item list-group-item-action">
                            <h6 class="mb-1">{{ related_post.title }}</h6>
                            <small class="text-muted">
                                <i class="fas fa-user me-1"></i>{{ related_post.author.username }} · 
                                <i class="fas fa-comments me-1"></i>{{ related_post.comments.count() }} 评论
                            </small>
                        </a>
                        {% endif %}
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<style>
.ink-card {
    border: none;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.ink-header {
    background-color: #f8f9fa;
    border-bottom: none;
    padding: 1.5rem;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.user-avatar-lg {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    object-fit: cover;
}

.default-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #e9ecef;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
}

.default-avatar-lg {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: #e9ecef;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.8rem;
}

.post-content {
    font-size: 1.1rem;
    line-height: 1.8;
}

.comment {
    padding: 1rem;
    background: #f8f9fa;
    border-radius: 8px;
    transition: all 0.2s ease;
}

.comment:hover {
    background: #f1f3f5;
}

.comment-content {
    font-size: 0.95rem;
    line-height: 1.5;
    color: #495057;
}

.ink-input {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 0.75rem;
    transition: all 0.3s ease;
}

.ink-input:focus {
    border-color: #6c757d;
    box-shadow: 0 0 0 0.2rem rgba(108, 117, 125, 0.25);
}

.list-group-item {
    border: none;
    padding: 1rem;
    margin-bottom: 2px;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}
</style>

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 处理代码块，为显示提供更好的格式和高亮
        const postContent = document.querySelector('.post-content');
        if (postContent) {
            let content = postContent.innerHTML;
            
            // 使用正则表达式查找所有代码块
            const codeBlockRegex = /```([\w-]*)\n([\s\S]*?)```/g;
            const processedContent = content.replace(codeBlockRegex, function(match, language, code) {
                // 如果指定了语言，添加语言类
                const langClass = language ? ` class="language-${language}"` : '';
                return `<pre><code${langClass}>${code.trim()}</code></pre>`;
            });
            
            // 更新内容
            postContent.innerHTML = processedContent;
            
            // 应用高亮
            document.querySelectorAll('pre code').forEach(block => {
                hljs.highlightElement(block);
            });
        }
        
        // 查找内容中的代码块进行处理
        const codeBlocks = document.querySelectorAll('pre code');
        
        // 处理每个代码块
        codeBlocks.forEach(function(block) {
            // 应用高亮
            hljs.highlightElement(block);
        });
        
        // 删除帖子
        window.deletePost = function() {
            if (confirm('确定要删除这篇帖子吗？此操作不可撤销。')) {
                fetch('/post/{{ post.id }}/delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = '{{ url_for("forum") }}';
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除操作出错');
                });
            }
        };
        
        // 删除评论
        window.deleteComment = function(commentId) {
            if (confirm('确定要删除这条评论吗？此操作不可撤销。')) {
                fetch('/comment/' + commentId + '/delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 刷新页面显示更改
                        window.location.reload();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除操作出错');
                });
            }
        };
        
        // 聚焦到评论输入框
        window.focusComment = function() {
            document.getElementById('comment-input').focus();
        };
    });

    function toggleLike() {
        fetch(`/post/{{ post.id }}/like`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const likeBtn = document.getElementById('likeBtn');
                const likeText = document.getElementById('likeText');
                const likeCount = document.getElementById('likeCount');
                
                if (data.action === 'liked') {
                    likeBtn.classList.remove('btn-outline-primary');
                    likeBtn.classList.add('btn-primary');
                    likeText.textContent = '已点赞';
                } else {
                    likeBtn.classList.remove('btn-primary');
                    likeBtn.classList.add('btn-outline-primary');
                    likeText.textContent = '点赞';
                }
                likeCount.textContent = `(${data.likes})`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请稍后重试');
        });
    }

    function toggleFavorite() {
        fetch(`/post/{{ post.id }}/favorite`, {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const favoriteBtn = document.getElementById('favoriteBtn');
                const favoriteText = document.getElementById('favoriteText');
                const favoriteCount = document.getElementById('favoriteCount');
                
                if (data.action === 'favorited') {
                    favoriteBtn.classList.remove('btn-outline-primary');
                    favoriteBtn.classList.add('btn-primary');
                    favoriteText.textContent = '已收藏';
                } else {
                    favoriteBtn.classList.remove('btn-primary');
                    favoriteBtn.classList.add('btn-outline-primary');
                    favoriteText.textContent = '收藏';
                }
                favoriteCount.textContent = `(${data.favorites})`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请稍后重试');
        });
    }
</script>
{% endblock %}
{% endblock %} 